<template>
  <div v-loading="pageLoading">
    <!-- 类型 -->
    <ul class="el-form__search">
      <li v-for="(item, index) in pageData.vodType" :key="index">
        <el-tag effect="plain">{{ item.typeName }}</el-tag>

        <el-popover placement="right" trigger="click">
          <el-cascader
            v-model="item.typeVal"
            :options="options"
            :props="{ label: 'typeName', value: 'id' }"
            clearable
          />
          <template #reference>
            <el-tag v-if="item.typeVal" type="success" size="mini" class="bind">
              [ {{ deepSearch(item.typeVal, options) }} ]
            </el-tag>
            <span v-else class="bind">[ 绑定 ]</span>
          </template>
        </el-popover>
      </li>
      <div class="bind-btn">
        <el-button
          :loading="bindLoading"
          type="primary"
          plain
          @click="bindType"
        >
          绑定分类
        </el-button>
      </div>
    </ul>

    <!-- 列表 -->
    <div class="collect">
      <div class="collect-data">
        <el-date-picker
          v-model="dataPickVal"
          type="daterange"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="shortcuts"
        />
        <el-button type="primary" @click="handleCollect">采 集</el-button>
        <el-button type="primary">采集全部</el-button>
      </div>
      <div class="search">
        <el-input v-model="collectWd" placeholder="请输入关键词" />
        <el-button :disabled="searchLoading" @click="handleSearch(false)">
          搜 索
        </el-button>
        <el-button :disabled="searchLoading" @click="handleSearch(true)">
          重 置
        </el-button>
      </div>
    </div>
    <el-table v-loading="searchLoading" stripe border :data="pageData.vod.list">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="vodName" label="名称" />
      <el-table-column prop="vodNote" label="更新状态">
        <template #default="{ row }">
          <el-tag type="success">
            {{ row.vodNote ? row.vodNote : '暂无状态' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="vodType" label="类型" />
      <el-table-column prop="updatedAt" label="更新时间" />
      <el-table-column label="操作">
        <template #default>
          <el-button type="text"> 采集 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      layout="prev, pager, next"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import {
  collect,
  collectPage,
  vodType,
  collectBindType,
  vodCreat
} from '@i/vod'
import { reactive, toRefs, onMounted, getCurrentInstance, computed } from 'vue'

export default {
  setup() {
    const { ctx } = getCurrentInstance()

    const listUrl = computed(() => {
      return `${page.collectUrl}?ac=list&pg=${page.pagination.currentPage}&wd=${page.collectWd}`
    })

    const collectUrl = computed(() => {
      return `${page.collectUrl}?ac=videolist&pg=${page.pagination.currentPage}&wd=${page.collectWd}&h=${page.collectH}`
    })

    const type = reactive({
      options: [],
      async vodType() {
        try {
          type.options = await vodType()
        } catch (error) {
          console.log(error)
        }
      },
      deepSearch(target, tree) {
        const res = target[target.length - 1]
        let path = ''
        tree
          .filter(item => {
            return item.id === target[0]
          })
          .forEach(item => {
            if (item.id === res) {
              path = item.typeName
            } else if (item.children) {
              path = `${path}${item.typeName} / ${type.deepSearch(
                [res],
                item.children
              )}`
            }
          })
        return path
      }
    })

    const page = reactive({
      id: '',
      collectUrl: '',
      collectWd: '',
      collectH: '',
      dataPickVal: '',
      pageData: {
        vodType: [],
        vod: {
          list: []
        }
      },
      pagination: {
        currentPage: 1,
        pageSize: 40,
        total: 0
      },
      pageLoading: false,
      bindLoading: false,
      searchLoading: false,
      shortcuts: [
        {
          text: '最近一周',
          value: (() => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
          })()
        },
        {
          text: '最近一个月',
          value: (() => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
          })()
        },
        {
          text: '最近三个月',
          value: (() => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
          })()
        }
      ],
      isWhichLoading(isSearch, status) {
        if (isSearch) {
          page.searchLoading = status
        } else {
          page.pageLoading = status
        }
      },
      async getPage(isSearch = false) {
        try {
          page.isWhichLoading(isSearch, true)
          const data = await collectPage({
            collectUrl: listUrl.value
          })

          if (!isSearch) {
            const { collectBindType } = await collect({ id: page.id })
            data.vodType.forEach(item => {
              collectBindType.forEach(type => {
                if (item.typeName === type.targetTypeName) {
                  item.typeVal = type.sourceTypeId
                }
              })
            })
            // 类型
            page.pageData.vodType = data.vodType
          }

          page.pageData.vod = data.vod
          page.pagination.currentPage = data.vod.page
          page.pagination.pageSize = data.vod.pagesize
          page.pagination.total = data.vod.recordcount
          page.isWhichLoading(isSearch, false)
        } catch (error) {
          page.isWhichLoading(isSearch, false)
          throw error
        }
      },
      async bindType() {
        try {
          page.bindLoading = true
          const bindType = page.pageData.vodType
            .filter(item => {
              return item.typeVal
            })
            .map(item => {
              return {
                sourceTypeId: item.typeVal,
                targetTypeName: item.typeName
              }
            })

          await collectBindType({
            id: page.id,
            collectBindType: bindType
          })
          page.bindLoading = false
          ctx.$message({
            message: '绑定类型成功',
            type: 'success'
          })
        } catch (error) {
          page.bindLoading = false
          throw error
        }
      },
      // 搜索
      handleSearch(reset) {
        if (reset) {
          page.pagination = {
            currentPage: 1,
            pageSize: 40,
            total: 0
          }
          page.collectWd = ''
          page.collectH = ''
        }
        page.getPage(true)
      },
      handleCurrentChange(val) {
        page.pagination.currentPage = val
        page.getPage(true)
      },
      async handleCollect() {
        page.collectH =
          (new Date(page.dataPickVal[1]).getTime() -
            new Date(page.dataPickVal[0]).getTime()) /
          1000 /
          60 /
          60

        const res = await vodCreat({ collectUrl: collectUrl.value })
        console.log(res)
      }
    })

    onMounted(() => {
      const queryInfo = ctx.$router.currentRoute.value.query
      page.id = queryInfo.id
      page.collectUrl = decodeURI(queryInfo.collectUrl)
      type.vodType()
      page.getPage(false)
    })

    return {
      ...toRefs(page),
      ...toRefs(type)
    }
  }
}
</script>

<style lang="scss" scoped>
ul {
  list-style: none;
  padding: 0;
  margin: 0 auto 24px;
  .bind-btn {
    width: 100%;
    text-align: right;
    .el-button {
      margin: 14px;
    }
  }
  li {
    font-size: 12px;
    color: rgb(58, 56, 56);
    width: 185px;
    margin: 10px;
    text-align: left;
    list-style: none;
    display: inline-block;
    .bind {
      margin-left: 4px;
      cursor: pointer;
    }
  }
}
.collect {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .collect-data {
    display: flex;
    align-items: center;
    :deep().el-date-editor {
      width: 300px;
      margin-right: 10px;
    }
  }
  .search {
    width: 360px;
    .el-input {
      width: 200px;
      margin-right: 10px;
    }
  }
}
</style>
